package com.digitalhuman.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;

import com.digitalhuman.model.*;
import com.digitalhuman.service.OpenAIService;

@RestController
@RequestMapping("/api/chat")
public class ChatController {
    
    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);
    
    @Autowired
    private OpenAIService openAIService;
    
    @PostMapping("/message")
    public ResponseEntity<ChatResponse> chat(@RequestBody ChatRequest request) {
        try {
            logger.info("Received chat request: {}", request.getMessage());
            
            if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
                logger.warn("Empty message received");
                return ResponseEntity
                    .badRequest()
                    .body(new ChatResponse("Message cannot be empty"));
            }
            
            logger.debug("Calling OpenAI service...");
            String response = openAIService.generateResponse(request.getMessage());
            logger.info("Generated response: {}", response);
            
            if (response.startsWith("Error:")) {
                logger.error("Error from OpenAI service: {}", response);
                return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ChatResponse(response));
            }
            
            return ResponseEntity.ok(new ChatResponse(response));
        } catch (Exception e) {
            logger.error("Error processing chat request", e);
            String errorMessage = String.format("Server error: %s - %s", 
                e.getClass().getSimpleName(), e.getMessage());
            return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new ChatResponse(errorMessage));
        }
    }
    
    @MessageMapping("/speech")
    @SendTo("/topic/speech")
    public SpeechResponse handleSpeech(SpeechRequest request) {
        return new SpeechResponse(request);
    }
} 